import { Builder, By, Key } from 'selenium-webdriver'
import delay from 'delay'
import fs from 'fs'

const driver = new Builder().forBrowser('chrome').build()
driver.manage().window().maximize()

let low = 0
let mid = 0
let high = 0

const cities = ['北京', '上海', '广州', '深圳', '武汉']
let cityIndex = 0

async function start() {
  await driver.get('https://www.lagou.com')
  driver.manage().deleteAllCookies()
  const cookies = JSON.parse(fs.readFileSync('./cookies.json', 'utf-8'))
  cookies.forEach(async cookie => {
    await driver.manage().addCookie(cookie)
  })
  await driver.get('https://www.lagou.com')

  await driver.findElement(By.css('#cboxLoadedContent .tab.focus')).click()
  await driver.findElement(By.css('#search_input')).sendKeys('前端', Key.ENTER)

  await delay(2000)
  const cityElements = await driver.findElements(By.css('.option__2xJt5'))
  cityElements.forEach(async ele => {
    const text = await ele.getText()
    if (text === cities[cityIndex]) {
      await ele.click()
    }
  })
  await getData()
}

start()

let currentPage = 1
const maxPage = 30
const results = []
async function getData() {
  console.log(`正在获取${cities[cityIndex]}的第${currentPage}页数据`)
  await delay(2000)
  const items = await driver.findElements(By.css('.item__10RTO'))
  const moneys = await Promise.all(items.map(async item => item.findElement(By.css('.money__3Lkgq')).getText()))
  // console.log(moneys)
  moneys.forEach(money => {
    const salary = money.split('-')[0].slice(0, -1)
    salary < 10 && low++
    salary >= 10 && salary < 20 && mid++
    salary >= 20 && high++
  })
  console.log(low, mid, high)

  // 判断是否到最后一页
  if (currentPage < maxPage) {
    try {
      await driver.findElement(By.css('.lg-pagination-next > .lg-pagination-item-link')).click()
    } catch(e) {
      delay(1000)
      await driver.findElement(By.css('.lg-pagination-next > .lg-pagination-item-link')).click()
    }
    currentPage++
    getData()
  } else {
    // 记录信息
    results.push({
      city: cities[cityIndex],
      low,
      mid,
      high
    })

    console.log(results)
    fs.writeFileSync('results.json', JSON.stringify(results))

    // 判断还有没有城市
    if (!cities[++cityIndex]) return

    await delay(1000)

    const cityElements = await driver.findElements(By.css('.option__2xJt5'))
    for (let i = 0; i < cityElements.length; i++) {
      const ele = cityElements[i]
      const text = await ele.getText()
      if (text === cities[cityIndex]) {
        await ele.click()
        break
      }
    }

    low = mid = high = 0
    currentPage = 1

    getData()
  }
}